export default {
  namespaced: true,
  state: {
    cartList: wx.getStorageSync('cart') || [],
    address:wx.getStorageSync('address')|| {
            userName: '',
            telNumber: '',
            infoAddress: ''
          }
  },
  mutations: {
    // 添加商品  从商品详情添加商品
    addCart(state, goods) {
      //console.log(state.cartList, 66666)
      // 判断需要添加的商品在 cartList中是否存在  如果存在就直接更新数量  否则就追加商品数据对象

      var index = state.cartList.findIndex(item => item.goods_id == goods.goods_id)
      console.log(index, 7777)
      if (index == -1) {
        state.cartList.push(goods)
      } else {
        state.cartList[index].goods_number += 1
      }
      wx.setStorage({
        key: "cart",
        data: state.cartList
      })
    },

    updateState(state, goods) {
      //  改变状态选中和未选中   
      var index = state.cartList.findIndex(item => item.goods_id == goods.goods_id)

      state.cartList[index].goods_state = !goods.goods_state
      wx.setStorage({
        key: "cart",
        data: state.cartList
      })

    },
    updateNumber(state, goods) {
      //    改变数量
      var index = state.cartList.findIndex(item => item.goods_id == goods.goods_id)

      state.cartList[index].goods_number = goods.goods_number
      wx.setStorage({
        key: "cart",
        data: state.cartList
      })


    },
    delItem(state, goods_id) {
      //  [1,2,3,4,5]  4
      state.cartList=state.cartList.filter(item => item.goods_id !== goods_id)
     // console.log(state.cartList,8888888)
      wx.setStorage({
        key: "cart",
        data: state.cartList
      })
    },
    
    //  全选和反选
    changeState(state,flag){
      state.cartList.forEach(item=>{
        item.goods_state=flag
      })
    },
    
    //  收货地址
    UpdateAddress(state,address){
      state.address=address
      wx.setStorage({
        key: "address",
        data: address
      })
    }
  },
  getters: {
    total(state) {
      var sum = 0
      state.cartList.forEach(item => {
        sum += item.goods_number
      })
      return sum
    },
    //  列表状态获取
    allCheckFlag(state){
      var  flagTrueLength=state.cartList.filter(item => item.goods_state).length
      if(state.cartList.length==flagTrueLength){
        //  全选
        return  true
      }else{
        //  不全选
        return false
      }
    },
    
    //  总数量
    allCheckNum(state){
      var  allSum=0
      state.cartList.filter(item=>item.goods_state).forEach(item2=>{
        allSum+=item2.goods_number
      })
      return allSum
    },
    //  总价钱
    subTotal(state){
      // var newARR=state.cartList.filter(item => item.goods_state)  //  所有选中状态的数据
      // return newARR.reduce((total, item)=>{ 
      //   return total+ item.goods_number*item.goods_price
      // },0)
      return state.cartList.filter(item => item.goods_state).reduce((total, item)=>(total+ item.goods_number*item.goods_price),0)
    }
  }
}
